#!/usr/bin/perl

# Stop us from shooting outselves in the foot
use strict;
use warnings;
use FindBin qw($Bin);
use lib "$Bin";

use MDBUtils;
use MDBAWS;
use MDBWP;

use IPC::Run qw( run );

# Configuration
my $queue = MDBAWS::sqs_get_queue("clamav");

while (1) {
    my $msg = MDBAWS::sqs_get_message($queue);

    if ( !defined($msg) ) {
        print "DEBUG: No tickets in the queue, quiting...\n";
        exit(0);
    }
    else {
        print "DEBUG: Picked up SQS ticket: " . $msg->MessageBody() . "\n";

        my $metadata = MDBAWS::sdb_get_metadata( $msg->MessageBody() );

        if (   defined( $metadata->{'sha256'} )
            && defined( $metadata->{'vt_ClamAV'} ) )
        {
            if ( $metadata->{'vt_ClamAV'} eq "-" ) {
                my $new_metadata;

                $new_metadata->{'sha256'} = $metadata->{'sha256'};

                $new_metadata->{'clamav_sig_hdb'} =
                    $metadata->{'md5'} . ":"
                  . $metadata->{'size'} . ":"
                  . $metadata->{'original_filename'};

                MDBAWS::sdb_put_metadata($new_metadata);

                # Create SQS Ticket(s)
                MDBAWS::sqs_put_queue( "clamav", $msg->MessageBody() );
            }
        }

        print "DEBUG: Deleting SQS ticket: " . $msg->MessageBody() . "\n";
        $queue->DeleteMessage( $msg->ReceiptHandle() );
    }
}
